package controller.commands;
import controller.Constants;
import java.util.ArrayList;
import model.graphic.objects.AbstractHandle;
import model.graphic.objects.AbstractOutPort;
import model.graphic.objects.GConnection;
import model.graphic.objects.GDispatcher;
import model.graphic.objects.GHandleConnection;
import model.graphic.objects.GOutput;
import model.graphic.objects.GOutputPort;
import model.graphic.objects.GTriggerConnection;

/**
 *
 * @author Ben
 */
public class ReplaceConnectionCommand  extends BasicCommand {
    private GConnection connection;

    public ReplaceConnectionCommand(GConnection connection) {
        this.connection = connection;
    }

    @Override
    public void execute() {
        ArrayList<BasicCommand> commands = new ArrayList<BasicCommand>(2);
        String type = null;
        AbstractOutPort aop = null;
        AbstractHandle freeOutput = null;
        if(GHandleConnection.class.isAssignableFrom(connection.getClass())){
            aop = (GOutputPort) ((GHandleConnection)connection).getOutput().getBase();
            type = Constants.getOutputString();
            freeOutput = (GOutput)gmodel.getAttachedObjects(aop, type).iterator().next();
            ((GOutput)freeOutput).adjustLine(connection.getSource().getX() - 15/2,
                                connection.getSource().getY() + 15/2);
        }else if(GTriggerConnection.class.isAssignableFrom(connection.getClass())){
            aop = ((GTriggerConnection)connection).getDispatcher();
            type = Constants.getDispatcherString();
            freeOutput = (GDispatcher)gmodel.getAttachedObjects(aop, type).iterator().next();
            ((GDispatcher)freeOutput).adjustLine(connection.getTarget().getX() - 15,
                                connection.getTarget().getY() + 15/2);
        }
        freeOutput.setHighlighted(true);
        commands.add(new DetachConnectionCommand(connection));
        commands.add(new DeleteCommand(connection));
        gview.notifyObservers(new MacroCommand(commands));
    }
   
}
